package com.example.compose.utils

import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.example.compose.App
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

/**
 * DataStore轻量级存储类
 * @author xiaotie https://www.cnblogs.com/xiao-tie/ 2022/8/1
 */
object DataStoreManager {
    private val Context.dataStore by preferencesDataStore("compose_test")

    private val nameKey = stringPreferencesKey("name")
    private val logcatFileKey = stringPreferencesKey("logcatFile")
    private val upDataVersionKey = stringPreferencesKey("upDataVersion")


    suspend fun saveName(name: String){
        App().getContext().dataStore.edit { preferences->
            preferences[nameKey] = name
        }
    }

    suspend fun saveUpDataVersion(upDataVersion: String){
        App().getContext().dataStore.edit { preferences->
            preferences[upDataVersionKey] = upDataVersion
        }
    }

    suspend fun saveLogcatFile(logcatFile: String){
        App().getContext().dataStore.edit { preferences->
            preferences[logcatFileKey] = logcatFile
        }
    }

    val name: Flow<String> = App().getContext().dataStore.data.map { preferences-> preferences[nameKey] ?: "" }

    val logcatFile: Flow<String> = App().getContext().dataStore.data.map { preferences-> preferences[logcatFileKey] ?: "" }

    val upDataVersion: Flow<String> = App().getContext().dataStore.data.map { preferences-> preferences[upDataVersionKey] ?: "0,0,0" }

}